package userservicelogic

import (
	"context"
	"database/sql"
	"fmt"
	"regexp"
	"smile-sunshine-micorservice/rpc/User/db/crud"
	"smile-sunshine-micorservice/rpc/User/internal/svc"
	"smile-sunshine-micorservice/rpc/User/internal/utils/password"
	"smile-sunshine-micorservice/rpc/User/pb/zipTako.com/SmileSunshine/user"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	UsersModel crud.UsersModel
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		UsersModel: crud.NewUsersModel(svcCtx.SqlConn, svcCtx.CacheConf),
	}
}

// Register 用户注册
func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.RegisterResponse, error) {

	l.Logger.Infof("收到注册请求，用户名：%s，邮箱：%s", in.Username, in.Email)

	// 1. 参数验证
	if err := l.validateRegisterRequest(in); err != nil {
		return &user.RegisterResponse{
			Success: false,
			Message: err.Error(),
		}, nil
	}

	// 2. 检查邮箱是否已存在
	_, err := l.UsersModel.FindOneByEmail(l.ctx, in.Email)
	if err == nil {
		return &user.RegisterResponse{
			Success: false,
			Message: "邮箱已被注册",
		}, nil
	}
	// 2. 检查手机是否已存在
	if in.Phone != "" {
		_, err = l.UsersModel.FindOneByPhone(l.ctx, sql.NullString{
			String: in.Phone,
			Valid:  true,
		})
		if err == nil {
			return &user.RegisterResponse{
				Success: false,
				Message: "手机号已被注册",
			}, nil
		}
	}

	// 3. 生成密码哈希
	hashedPassword, err := password.GenerateHashPassword(in.Password)
	if err != nil {
		l.Logger.Errorf("生成密码哈希失败：%v", err)
		return &user.RegisterResponse{
			Success: false,
			Message: "注册失败，请稍后重试",
		}, nil
	}

	// 4. 创建用户
	newUser := &crud.Users{
		Username:     in.Username,
		HashPassword: hashedPassword,
		Email:        in.Email,
		Phone: sql.NullString{
			String: in.Phone,
			Valid:  in.Phone != "",
		},
	}

	result, err := l.UsersModel.Insert(l.ctx, newUser)
	if err != nil {
		l.Logger.Errorf("创建用户失败：%v", err)
		return &user.RegisterResponse{
			Success: false,
			Message: "注册失败，请稍后重试",
		}, nil
	}

	userId, err := result.LastInsertId()
	if err != nil {
		l.Logger.Errorf("获取用户ID失败：%v", err)
		return &user.RegisterResponse{
			Success: false,
			Message: "注册失败，请稍后重试",
		}, nil
	}

	// 5. 返回成功响应
	return &user.RegisterResponse{
		Success: true,
		Message: "注册成功",
		UserId:  userId,
	}, nil
}

// validateRegisterRequest 验证注册请求参数
func (l *RegisterLogic) validateRegisterRequest(in *user.RegisterRequest) error {

	// 将邮箱转换为小写
	in.Email = strings.ToLower(in.Email)

	// 验证用户名
	if len(in.Username) < 3 || len(in.Username) > 20 {
		return fmt.Errorf("用户名长度必须在3-20个字符之间")
	}

	// 验证密码
	if len(in.Password) < 6 || len(in.Password) > 20 {
		return fmt.Errorf("密码长度必须在6-20个字符之间")
	}

	// 验证邮箱格式（邮箱已经转换为小写）
	emailPattern := `^[a-zA-Z0-9._%+-]+@ziptako.com$`
	if !regexp.MustCompile(emailPattern).MatchString(in.Email) {
		return fmt.Errorf("邮箱格式不正确")
	}

	// 验证手机号
	if in.Phone != "" {
		phonePattern := `^1[3-9]\d{9}$`
		if !regexp.MustCompile(phonePattern).MatchString(in.Phone) {
			return fmt.Errorf("手机号格式不正确")
		}

	}

	return nil
}
